package com.example.concurrentprogramming8016.thread.cas;

import com.example.concurrentprogramming8016.thread.Atomic.AtomicReferenceTest;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

/**
 * @author liyanhao
 * @Date 2023-01-04 1:48
 */
@Slf4j
public class ABATest {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(1);
        new Thread(() -> {
            int value = atomicInteger.get();
            log.debug("thread1 read value:" + value);

            //阻塞1秒
            LockSupport.parkNanos(1000000000L);
            //thread1 通过CAS修改value值为3
            if (atomicInteger.compareAndSet(value, 3)) {
                log.debug("thread1 update from" + value + "to 3");
            } else {
                log.debug("thread1 update fail !");
            }
        }, "thread1").start();

        new Thread(() -> {
            int value = atomicInteger.get();
            log.debug("thead2 read value:" + value);
            if (atomicInteger.compareAndSet(value, 2)) {
                value = atomicInteger.get();
                log.debug("thread2 read value:" + value);
                //thread2 通过cas把value改成1
                if (atomicInteger.compareAndSet(value, 1)) {
                    log.debug("thread2 update value:" + value + "to" + 1);
                }
            }
        }, "thrad2").start();

    }
}
